package com.mx.base.language.script.remote

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * @author: xiao.ma
 * Date: 2022/2/9 17:51
 * Desc:
 */

class NetWork {
    private val defaultTimeout = 10L
    private var mRetrofit: Retrofit? = null
    private var apiMap = mutableMapOf<String, Any?>()

    var baseUrl = "http://localhost:8080"

    private object SingletonHolder {
        val holder = NetWork()
    }

    companion object {
        val instance = SingletonHolder.holder
    }

    fun <T> getApi(apiClass: Class<T>): T {
        var result: T
        synchronized(lock = apiMap) {
            result = apiMap[apiClass.name] as T
            if (result == null) {
                result = configRetrofit(apiClass)
                apiMap[apiClass.name] = result
            }
        }
        return result
    }

    private fun <T> configRetrofit(service: Class<T>): T {
        mRetrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(configClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return mRetrofit!!.create(service)
    }

    private fun configClient(): OkHttpClient {
        val loginInterceptor = HttpLoggingInterceptor()
        loginInterceptor.level = HttpLoggingInterceptor.Level.BODY
        val okHttpClientBuilder = OkHttpClient.Builder()
     //   if (BuildConfig.DEBUG) {
            okHttpClientBuilder.addNetworkInterceptor(loginInterceptor) //添加retrofit日志打印
     //   }
        okHttpClientBuilder.connectTimeout(defaultTimeout, TimeUnit.SECONDS)
        okHttpClientBuilder.readTimeout(defaultTimeout, TimeUnit.SECONDS)
        okHttpClientBuilder.writeTimeout(defaultTimeout, TimeUnit.SECONDS)
        return okHttpClientBuilder.build()
    }

    /**
     * 删除不再需要的api
     */
    fun <T> clearApi(apiClass: Class<T>) {
        synchronized(apiMap) {
            if (apiMap.containsKey(apiClass.name)) {
                apiMap.remove(apiClass.name)
            }
        }
    }

}